import { createAppSlice } from "@/lib/createAppSlice"
import { ReportType } from "@/type/report"
import { PayloadAction } from "@reduxjs/toolkit"

const initialState: { data: ReportType[] } = {
    data: []
}

export const reportSlice = createAppSlice({
    name: "report",
    initialState,
    reducers: (create) => ({
        setReportData: create.reducer((state, action: PayloadAction<ReportType[]>) => {
            state.data = action.payload
        }),
        updateReportData: create.reducer((state, action: PayloadAction<ReportType>) => {
            const detail = action.payload
            const result = state.data.findIndex((item) => item.id == detail.id)
            if (result != -1) {
                state.data[result] = detail
            } else {
                state.data.push(action.payload)
            }
        }),
        deleteById: create.reducer((state, action: PayloadAction<number>) => {
            state.data = state.data.filter((item) => item.id != action.payload)
        }),
    }),
    selectors: {
        selectReport: (report) => report.data,
        getLastId: (report) => report.data[report.data.length - 1]?.id ?? -1
    }
})

export const { setReportData, updateReportData, deleteById } = reportSlice.actions

export const { selectReport, getLastId } = reportSlice.selectors
